package org.r505.chatroom.global.core;

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.r505.chatroom.global.controller.ControllerFactory;


public class ClassScaner {
	private Document document = null;
	
	public ClassScaner(){
		SAXReader reader = new SAXReader(); 
		try {
			document = reader.read(new File(this.getClass().getResource("/").getPath() + "/websocket.xml"));
			getController();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	public ClassScaner(String fileName){ 
		SAXReader reader = new SAXReader(); 
		try {
			document = reader.read(new File(fileName));
			getController();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 获取并处理Controller结点
	 */
	private void getController(){
		//获取所有controller结点
		List<Element> controllers = document.getRootElement().elements("controller");
		for(Element controller : controllers){
			try {
				//获取id属性
				String id = controller.attributeValue("id"); 
				//获取class属性
				String clazzName = controller.attributeValue("class");
				List<Element> mappings = controller.elements("mapping");
				Class<?> clazz = Class.forName(clazzName); //获取controller类型
				Object object = clazz.newInstance();
				InstanceFactory.createInstance(id, object); //保存实例
				for(Element mapping : mappings){
					String mappingStr = mapping.attributeValue("mapping");
					String method = mapping.attributeValue("method");
					ControllerFactory.createMappingId(mappingStr, id);
					ControllerFactory.createMappingMethod(mappingStr, method);
				}
				
			} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | SecurityException e) {
				e.printStackTrace();
			}
		}
	}
}
